/* This program uses trail division to find primes */
import java.util.*;
import java.lang.Math;

public class PrimeGenerator implements Iterator<Integer>  {

	private static int n;
	static int[] primeSeries ;
	static int primeCounter;
	
	public static void main (String [ ] args) {
		// Make sure there is exactly one argument, an integer.
		// Store the argument, converted to an int, in n.
		try{
			if ((args.length != 1)){
			
				throw new IllegalArgumentException();
			
			}
			n = Integer.parseInt(args[0]);
		}
		catch(RuntimeException e){
			System.err.println("illegal input");
			System.exit(1);
		}
		
		PrimeGenerator primeGen = new PrimeGenerator (n);
		int mostRecentPrime = 2;
		while (primeGen.hasNext ( )) {
			mostRecentPrime = primeGen.next ( );
		}
		System.out.println("The nth prime is: " + mostRecentPrime + " where n was: " + n);
	}

	public PrimeGenerator (int n) {
		// Make sure n is positive; throw IllegalArgumentException if not.
		// Initialize the iterator of the first n prime numbers.
		try{
			if (n <= 0){
				throw new IllegalArgumentException();
				
			}
			primeSeries = new int[n] ;
			primeSeries[0]=2;
			primeCounter =0;
		}
		
		
		catch(RuntimeException e){
			System.err.println("n must be positive");
			System.exit(1);
			
		}
		
		
		
		

		
		
	}
	
	
	// Return true if there are more primes to return.
	public boolean hasNext ( ) {
		if (primeCounter < n-1 ){
			return true;
		}
		else{
			return false;
		}
	}
	
	// Return the next prime number.
	public Integer next()	{
		int i = 0;
		int trailNumber = primeSeries[primeCounter]+1;
		// within 2 to square root of trail number, try use each prime number to divide next integer
		while (primeSeries[i]<=Math.sqrt((double)trailNumber)){
			if (trailNumber % primeSeries[i] == 0){								
				trailNumber++;
				i = 0;
				continue;
			}
			i++;
			
		}
		primeCounter++;
		primeSeries[primeCounter]= trailNumber;
		return trailNumber;
		
			
	}

	

	// This is only here because the Iterator interface requires it.
	public void remove ( ) {		
	}
}
